"use strict";

import Vue from 'vue';
import axios from "axios";
import store from './../store'
import {Message} from 'element-ui'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || "http://localhost:3000"
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);
_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if(store.state.token){//如果store中有token  表明登录过了，则设置到请求头中
      config.headers.Authorization=store.state.token
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    // error status 处理
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
            error.response.data = '请求出错'
            break
        case 401:
            Message.warning({
                message: '授权失败，请重新登录'
            })
            store.commit('LOGIN_OUT')
            setTimeout(() => {
                window.location.reload()
            }, 1000)

            return
        case 403:
            error.response.data = '拒绝访问'
            break
        case 404:
            error.response.data = '请求错误,未找到该资源'
            break
        case 500:
            error.response.data = '服务器端出错'
            break
        }
    } else {
        error.response.data = '连接服务器失败'
    }
    Message.error(error.response.data)//如果报错 则提示错误信息
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
